package com.mall.widget;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.examination.mlib.bean.DefaultEntity;
import com.examination.mlib.bean.HomeDrugEntity;
import com.examination.mlib.constants.AllStringConstants;
import com.examination.mlib.constants.ClickApi;
import com.examination.mlib.constants.KitArouterConstants;
import com.examination.mlib.utils.LocationUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mall.MallUtils;
import com.mall.R;
import com.mall.bean.YHotSaleBean;
import com.mall.observer.MallObserver;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.GlideUtil;
import com.yilijk.base.utils.ListUtil;
import com.yilijk.base.utils.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MallHotView extends LinearLayout {
    private Context context;
    private View contentView;
    private RecyclerView recyclerView;
    private List<HomeDrugEntity.DrugItemData> hotList = new ArrayList<>();
    private HotAdapter hotAdapter;
    private YHotSaleBean bean;
    private TextView titleTv;
    private String doctorId;
    private View hotMareLl;
    private ImageView hotIconIv;
    private ImageView hotBgIv;
    private final Gson gson = new Gson();

    public MallHotView(Context context) {
        super(context);
        init(context);
    }

    public MallHotView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MallHotView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public MallHotView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        contentView = LayoutInflater.from(context).inflate(R.layout.view_mall_hot, this);
        recyclerView = contentView.findViewById(R.id.recycler_view);
        titleTv = contentView.findViewById(R.id.tv_title);
        hotMareLl = contentView.findViewById(R.id.ll_hot_more);
        hotIconIv = contentView.findViewById(R.id.icon_hot);
        hotBgIv = contentView.findViewById(R.id.bg_hot);

        recyclerView.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL, false));

        hotAdapter = new HotAdapter(context, hotList);
        recyclerView.setAdapter(hotAdapter);


    }

    public void setBean(YHotSaleBean bean, String doctorId) {
        this.bean = bean;
        this.doctorId = doctorId;
        titleTv.setText(bean.getTitle());
        hotList.clear();
        hotAdapter.notifyDataSetChanged();
        getHotDrugs(bean.getId());
        if (bean.getLogo() != null && !TextUtils.isEmpty(bean.getLogo().getImgUrl())) {
            GlideUtil.load(context, bean.getLogo().getImgUrl(), hotIconIv, R.mipmap.icon_hot);
        } else {
            hotIconIv.setImageResource(R.mipmap.icon_hot);
        }
        if (bean.getBackground() != null && !TextUtils.isEmpty(bean.getBackground().getImgUrl())) {
            GlideUtil.load(context, bean.getBackground().getImgUrl(), hotBgIv, R.mipmap.bg_hot);
        } else {
            hotBgIv.setImageResource(R.mipmap.bg_hot);
        }
        if (!TextUtils.isEmpty(bean.getTitleColor())) {
            titleTv.setTextColor(Color.parseColor(bean.getTitleColor()));
        } else {
            titleTv.setTextColor(getResources().getColor(R.color.hot_title));
        }
        ClickUtils.setFastOnClickListener(hotMareLl, new OnClickListener() {
            @Override
            public void onClick(View v) {
                ClickUtils.sendEvent(ClickApi.Mall.click_drugshotmore, context, "首页药品热销品更多点击");
                Bundle bundle = new Bundle();
                bundle.putString("title", bean.getTitle());
//                bundle.putString("frontCategoryId", bean.getId());
                ArrayList<String> ids = new ArrayList<>();
                ids.add(bean.getId());
                bundle.putStringArrayList("frontCategoryIds", ids);
                if (!TextUtils.isEmpty(doctorId)) {
                    bundle.putString("doctorId", doctorId);
                }
                DefaultEntity.DataBean whCityBean = LocationUtils.getInstance().getWhCityBean();
                AMapLocation aMapLocation = LocationUtils.getInstance().getaMapLocation();
                if (whCityBean != null && !TextUtils.isEmpty(whCityBean.getProvinceName()) && !TextUtils.isEmpty(whCityBean.getCityName())) {
                    bundle.putString("whCity", whCityBean.getProvinceName() + "," + whCityBean.getCityName());
//                    paramsJSON.put("lat", whCityBean.getLat());
//                    paramsJSON.put("lng", whCityBean.getLng());
                } else if (aMapLocation != null && !TextUtils.isEmpty(aMapLocation.getProvince()) && !TextUtils.isEmpty(aMapLocation.getCity())) {
                    bundle.putString("whCity", aMapLocation.getProvince() + "," + aMapLocation.getCity());
//                    paramsJSON.put("lat", aMapLocation.getLatitude());
//                    paramsJSON.put("lng", aMapLocation.getLongitude());
                }
                MallUtils.push(context, KitArouterConstants.CART_DOCTORBUNDLE, KitArouterConstants.Cart.Retailers, bundle);
            }
        });
    }

    private void getHotDrugs(String id) {
        RequestParams params = new RequestParams();
        params.put("pageIndex", 1);
        params.put("pageSize", 10);
        params.put("doctorId", this.doctorId);
        params.put("containVirtualService", false);
//        params.put("frontCategoryId", "[" + id + "]");
        params.put("frontCategoryIds", id);
//        params.put("blockList", id);
//        ArrayList<String> ids = new ArrayList<>();
//        ids.add(id);
//        params.put("frontCategoryId", ids);
        params.put("scene", 1);

        HttpUtils.get(AllStringConstants.MallUrl.waterfallFlowList, params, new HttpCallBack<HomeDrugEntity>() {
            @Override
            public void onSuccess(HomeDrugEntity bean, int i) {

                if (i == 200 && bean != null && bean.getCode() == 200 && bean.getData() != null) {
                    List<HomeDrugEntity.DrugItemData> listBeans = bean.getData().getDataList();
                    hotList.clear();
                    hotList.addAll(listBeans);
                    hotAdapter.notifyDataSetChanged();
                }else if (bean != null && !TextUtils.isEmpty(bean.getMsg())) {
                    ToastUtils.showShort(bean.getMsg());
                }

//                String searchStr = gson.toJson(bean);
//                try {
//                    JSONObject jsonObject = new JSONObject(searchStr);
//                    if (jsonObject.has("code")) {
//                        int code = jsonObject.getInt("code");
//                        if (code == 200 && jsonObject.has("data")) {
//                            JSONObject dataJson = jsonObject.getJSONObject("data");
//                            if (dataJson != null && dataJson.has(id)) {
//                                JSONArray drugJsonArray = dataJson.getJSONArray(id);
//                                List<HomeDrugEntity.DrugItemData> listBeans = gson.fromJson(drugJsonArray.toString(), new TypeToken<List<HomeDrugEntity.DrugItemData>>() {
//                                }.getType());
//                                hotList.clear();
//                                hotList.addAll(listBeans);
//                                hotAdapter.notifyDataSetChanged();
//                            }
//                        }
//                    }
//
//                } catch (Throwable e) {
//                    e.printStackTrace();
//                }
////                if (i == 200 && bean != null && "200".equals(bean.getStatus()) && bean.getData() != null) {
////                    List<MallDrugBean.ListBean> listBeans = bean.getData().getList();
////                    hotList.clear();
////                    hotList.addAll(listBeans);
////                    hotAdapter.notifyDataSetChanged();
////                } else if (bean != null && !TextUtils.isEmpty(bean.getMessage())) {
////                    ToastUtils.showShort(bean.getMessage());
////                }

            }

            @Override
            public void onFailure(String s, int i) {
            }
        });
    }

    private class HotAdapter extends RecyclerView.Adapter {
        private Context context;
        private List<HomeDrugEntity.DrugItemData> hotList;

        public HotAdapter(Context context, List<HomeDrugEntity.DrugItemData> hotList) {
            this.context = context;
            this.hotList = hotList;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.view_item_hot, parent, false);
            return new HotVH(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof HotVH) {
                ((HotVH) holder).setData(position);
            }
        }

        @Override
        public int getItemCount() {
            return ListUtil.getSize(hotList);
        }
    }

    private class HotVH extends RecyclerView.ViewHolder {

        private final ImageView drugIv;
        private final TextView drugPriceTv;

        public HotVH(@NonNull View itemView) {
            super(itemView);
            drugIv = itemView.findViewById(R.id.iv_drug);
            drugPriceTv = itemView.findViewById(R.id.tv_drug_price);
        }

        public void setData(int position) {
            if (ListUtil.getSize(hotList) > position) {
                HomeDrugEntity.DrugItemData bean = hotList.get(position);
                GlideUtil.load(context, bean.getImageUrl(), drugIv, R.drawable.icon_default_square);
                drugPriceTv.setText(bean.getPrice());

                ClickUtils.setFastOnClickListener(itemView, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ClickUtils.sendEvent(ClickApi.Mall.click_drugshot, context, "首页药品热销品点击");
                        Bundle bundle = new Bundle();

                        if ("drug".equals(bean.getCommodityType())) {
                            bundle.putString("id", "" + bean.getDrugId());
                        } else {
                            bundle.putString("packetId", "" + bean.getPacketId());
                        }
                        if (!TextUtils.isEmpty(doctorId)) {
                            bundle.putString("doctorId", "" + doctorId);
                        }
                        ALog.e("oakkk", "bundle: " + bundle.toString());
                        MallUtils.push(context,
                                KitArouterConstants.CART_DOCTORBUNDLE,
                                KitArouterConstants.Cart.DrugDetail,
                                bundle);
                    }
                });

            }
        }
    }

}
